<template>
    <!-- 登录弹窗遮罩 -->
    <div v-if="visible" class="login-modal-overlay" @click="handleOverlayClick">
        <!-- 登录弹窗主体 -->
        <div class="login-modal" @click.stop>
            <!-- 关闭按钮 -->
            <button class="close-button" @click="handleClose">×</button>

            <div v-if="!showRegisterForm" class="login-form">
                <!-- 登录标签页 -->
                <div class="login-tabs">
                    <div class="tab-header">
                        <div class="tab-item" :class="{ active: activeTab === 'account' }"
                            @click="activeTab = 'account'">
                            账号登录
                        </div>
                        <div class="tab-item" :class="{ active: activeTab === 'sms' }" @click="activeTab = 'sms'">
                            扫码登录
                        </div>
                    </div>

                    <div class="tab-content">
                        <!-- 账号登录内容 -->
                        <div v-if="activeTab === 'account'" class="tab-pane">
                            <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" label-width="0">
                                <el-form-item prop="account">
                                    <el-input v-model="loginForm.account" placeholder="用户名/手机号" size="large" @keydown.enter="handleEnter"
                                        class="login-input" />
                                </el-form-item>
                                <el-form-item prop="password">
                                    <el-input v-model="loginForm.password" type="password" placeholder="密码" size="large" @keyup.enter="handleLogin"
                                        show-password class="login-input" ref="passwordRef"/>
                                </el-form-item>
                                <el-form-item>
                                    <div style="display: flex;align-items: center;justify-content: flex-start;width: 100%;">
                                        <el-button type="primary" size="large" class="login-btn" :loading="loginLoading" @click="lockLogin">
                                            登录
                                        </el-button>
                                        <el-button size="large" class="cancel-btn" @click="handleClose">
                                            取消
                                        </el-button>
                                    </div>
                                    
                                </el-form-item>
                            </el-form>
                        </div>

                        <!-- 短信登录内容 -->
                        <div v-if="activeTab === 'sms'" class="tab-pane">
                            <div class="qrcode-login">
                                <div class="qrcode-container">
                                    <div class="qrcode-placeholder">
                                        <div class="qrcode-box">
                                            <div class="qrcode-inner"></div>
                                        </div>
                                        <p class="qrcode-text">请使用手机扫描二维码登录</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="login-footer">
                    <div class="footer-links">
                        <button class="footer-link">忘记密码？</button>
                    </div>
                    <div class="register-link">
                        <button @click="showRegisterForm = true" class="register-btn">免费注册用户</button>
                    </div>
                </div>
            </div>

            <div v-else class="register-form">
                <div class="register-header">
                    <h3 class="register-title">今生永恒网用户注册</h3>
                    <!-- <button class="header-close-btn" @click="handleClose">×</button> -->
                </div>

                <div class="register-content">
                    <el-form ref="registerFormRef" :model="registerForm" :rules="registerRules" label-width="0">
                        <el-form-item prop="account">
                            <el-input v-model="registerForm.account" placeholder="输入用户名" size="large"
                                class="register-input" />
                        </el-form-item>
                        <el-form-item prop="password">
                            <el-input v-model="registerForm.password" type="password" placeholder="登录密码 (6至20位)"
                                size="large" show-password class="register-input" />
                        </el-form-item>
                        <el-form-item prop="password_confirm">
                            <el-input v-model="registerForm.password_confirm" type="password" placeholder="确认密码"
                                size="large" show-password class="register-input" />
                        </el-form-item>
                        <el-form-item prop="nickname">
                            <el-input v-model="registerForm.nickname" placeholder="昵称或姓名" size="large"
                                class="register-input" />
                        </el-form-item>

                        <el-form-item>
                            <el-checkbox v-model="agreeTerms" class="terms-checkbox">
                                我已阅读并接受 <button class="terms-link">《今生永恒网服务条款》</button>
                            </el-checkbox>
                        </el-form-item>

                        <el-form-item>
                            <div class="register-buttons">
                                <el-button type="primary" size="large" class="submit-btn" :loading="registerLoading"
                                    @click="handleRegister">
                                    提交
                                </el-button>
                                <el-button size="large" class="cancel-btn" @click="showRegisterForm = false">
                                    取消
                                </el-button>
                            </div>
                        </el-form-item>
                    </el-form>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import type { FormInstance, InputInstance } from 'element-plus'
import { ref, reactive, watch } from 'vue'
import { ACCOUNT_KEY } from '@/enums/cacheEnums'
import { PageEnum } from '@/enums/pageEnum'
import { ElMessage } from 'element-plus'
import feedback from '@/utils/feedback'
import { useLockFn } from '@/hooks/useLockFn'
import useAppStore from '@/stores/modules/app'
import useUserStore from '@/stores/modules/user'
import cache from '@/utils/cache'
import { useRoute, useRouter } from 'vue-router'
const passwordRef = shallowRef<InputInstance>()
const appStore = useAppStore()
const userStore = useUserStore()
const route = useRoute()
const router = useRouter()
// Props
interface Props {
    modelValue: boolean
}

const props = withDefaults(defineProps<Props>(), {
    modelValue: false
})

// Emits
interface Emits {
    (e: 'update:modelValue', value: boolean): void
    (e: 'loginSuccess', userInfo?: any): void
    (e: 'registerSuccess', userInfo?: any): void
}

const emit = defineEmits<Emits>()

// 响应式数据
const visible = ref(false)
const showRegisterForm = ref(false)
const activeTab = ref('account')
const loginLoading = ref(false)
const registerLoading = ref(false)
const agreeTerms = ref(false)
const loginFormRef = ref()
const registerFormRef = ref()

// 登录表单数据
const loginForm = reactive({
    account: '',
    password: ''
})

// 注册表单数据
const registerForm = reactive({
    account: '',
    password: '',
    password_confirm: '',
    nickname: '',
    channel: '4'
})

// 登录表单验证规则
const loginRules = {
    account: [
        { required: true, message: '请输入用户名或手机号', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
    ]
}

// 注册表单验证规则
const registerRules = {
    account: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在6到20位之间', trigger: 'blur' }
    ],
    password_confirm: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        {
            validator: (rule: any, value: string, callback: Function) => {
                if (value !== registerForm.password) {
                    callback(new Error('两次输入密码不一致'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ],
    nickname: [
        { required: true, message: '请输入昵称或姓名', trigger: 'blur' },
        { min: 2, max: 20, message: '昵称长度在2到20个字符', trigger: 'blur' }
    ]
}

// 监听 modelValue 变化
watch(
    () => props.modelValue,
    (newVal) => {
        visible.value = newVal
    },
    { immediate: true }
)

// 监听 visible 变化
watch(
    () => visible.value,
    (newVal) => {
        emit('update:modelValue', newVal)
    }
)
// 回车按键监听
const handleEnter = () => {
    if (!loginForm.password) {
        return passwordRef.value?.focus()
    }
    handleLogin()
}

// 登录处理函数
const handleLogin = async () => {
    if (!loginFormRef.value) return

    try {
        await loginFormRef.value.validate()
        loginLoading.value = true

        // 这里应该调用实际的登录API
        // const res = await apiLogin(loginForm)
        // 模拟登录请求
        await userStore.login(loginForm)
        // await new Promise(resolve => setTimeout(resolve, 1000))

        // 登录成功后的处理
        feedback.msgSuccess('登录成功')
        emit('loginSuccess')
        handleClose()

    } catch (error) {
        console.error('登录失败:', error)
        feedback.msgError('登录失败，请检查用户名和密码')
    } finally {
        loginLoading.value = false
    }
}
// 登录处理
const { isLock, lockFn: lockLogin } = useLockFn(handleLogin)
// 注册处理函数
const handleRegister = async () => {
    if (!agreeTerms.value) {
        feedback.msgError('请先同意用户协议')
        return
    }
    if (!registerFormRef.value) return

    try {
        await registerFormRef.value.validate()
        registerLoading.value = true

        // 这里应该调用实际的注册API
        // const res = await apiRegister(registerForm)
        // 模拟注册请求
        await userStore.register({...registerForm});
        // await new Promise(resolve => setTimeout(resolve, 1000))

        // 注册成功后的处理
        feedback.msgSuccess('注册成功')
        emit('registerSuccess')
        showRegisterForm.value = false
        resetRegisterForm()

    } catch (error) {
        console.error('注册失败:', error)
        feedback.msgError('注册失败，请稍后重试')
    } finally {
        registerLoading.value = false
    }
}

// 关闭弹窗
const handleClose = () => {
    visible.value = false
    showRegisterForm.value = false
    resetLoginForm()
    resetRegisterForm()
}

// 重置登录表单
const resetLoginForm = () => {
    loginForm.account = ''
    loginForm.password = ''
    loginFormRef.value?.clearValidate()
}

// 重置注册表单
const resetRegisterForm = () => {
    registerForm.account = ''
    registerForm.password = ''
    registerForm.password_confirm = ''
    registerForm.nickname = ''
    agreeTerms.value = false
    registerFormRef.value?.clearValidate()
}

// 点击遮罩层关闭弹窗
const handleOverlayClick = () => {
    handleClose()
}

// 暴露方法给父组件
defineExpose({
    resetLoginForm,
    resetRegisterForm,
    handleClose
})
</script>

<style scoped>
/* 登录弹窗遮罩层 */
.login-modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 3008;
}

/* 登录弹窗主体 */
.login-modal {
    position: relative;
    width: 400px;
    background: #F5E6D3;
    border-radius: 8px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
    overflow: hidden;
}

/* 关闭按钮 */
.close-button {
    position: absolute;
    top: 10px;
    right: 15px;
    background: none;
    border: none;
    font-size: 30px;
    color: #8B4513;
    cursor: pointer;
    z-index: 10;
    width: 25px;
    height: 25px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.close-button:hover {
    color: #654321;
}

/* 登录表单样式 */
.login-form {
    background: #F5E6D3;
}

/* 标签页样式 */
.login-tabs {
    background: #F5E6D3;
}

.tab-header {
    display: flex;
    background: #D2B48C;
    border-radius: 8px 8px 0 0;
    gap: 0 2px;
}

.tab-item {
    /* flex: 1; */
    padding: 12px 20px;
    text-align: center;
    color: #8B4513;
    font-weight: 500;
    cursor: pointer;
    background: #D2B48C;
    /* border-radius: 8px 8px 0 0; */
    transition: all 0.3s ease;
}

.tab-item.active {
    background: #F5E6D3;
    color: #8B4513;
}
.tab-item:hover{
    background: #F5E6D3;
}
.tab-content {
    background: #F5E6D3;
    padding: 20px;
}

.tab-pane {
    /* min-height: 200px; */
}

/* 输入框样式 */
.login-input {
    /* margin-bottom: 15px; */
}

:deep(.login-input .el-input__wrapper) {
    border-radius: 6px;
    border: 1px solid #D2B48C;
    background: #fff;
}

/* 登录按钮样式 */
.login-btn {
    width: 48%;
    background: #D2B48C;
    border: none;
    border-radius: 4px;
    color: #fff;
    font-weight: 500;
    margin-right: 4%;
}

.login-btn:hover {
    background: #C19A6B;
}

.cancel-btn {
    width: 48%;
    border: 1px solid #D2B48C;
    border-radius: 4px;
    color: #8B4513;
    background: #fff;
}

.cancel-btn:hover {
    background: #F5F5F5;
}

/* 二维码登录样式 */
.qrcode-login {
    text-align: center;
    padding: 20px;
}

.qrcode-container {
    display: flex;
    justify-content: center;
    margin-bottom: 20px;
}

.qrcode-placeholder {
    text-align: center;
}

.qrcode-box {
    width: 120px;
    height: 120px;
    border: 2px solid #D2B48C;
    border-radius: 8px;
    margin: 0 auto 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #fff;
}

.qrcode-inner {
    width: 80px;
    height: 80px;
    background: #F0F0F0;
    border-radius: 4px;
}

.qrcode-text {
    color: #8B4513;
    font-size: 14px;
    margin: 0;
}

/* 登录底部样式 */
.login-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px 20px;
    background: #F5E6D3;
    border-top: 1px solid #E0D0C0;
}

.footer-link {
    background: none;
    border: none;
    color: #8B4513;
    text-decoration: none;
    font-size: 14px;
    cursor: pointer;
}

.footer-link:hover {
    color: #654321;
    text-decoration: underline;
}

.register-btn {
    background: none;
    border: none;
    color: #D2B48C;
    text-decoration: none;
    font-size: 14px;
    cursor: pointer;
}

.register-btn:hover {
    color: #C19A6B;
    text-decoration: underline;
}

/* 注册表单样式 */
.register-form {
    background: #F5E6D3;
    border-radius: 8px;
}

.register-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 20px 15px;
    background: #F5E6D3;
    border-bottom: 1px solid #E0D0C0;
}

.register-title {
    margin: 0;
    color: #8B4513;
    font-size: 18px;
    font-weight: 500;
}

.header-close-btn {
    background: none;
    border: none;
    font-size: 20px;
    color: #8B4513;
    cursor: pointer;
    padding: 0;
    width: 25px;
    height: 25px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.header-close-btn:hover {
    color: #654321;
}

.register-content {
    padding: 20px;
    background: #F5E6D3;
}

/* 注册输入框样式 */
.register-input {
    /* margin-bottom: 15px; */
}

:deep(.register-input .el-input__wrapper) {
    border-radius: 8px;
    border: 1px solid #D2B48C;
    background: #fff;
}

/* 条款复选框样式 */
.terms-checkbox {
    margin-bottom: 20px;
}

:deep(.terms-checkbox .el-checkbox__label) {
    color: #8B4513;
}

.terms-link {
    background: none;
    border: none;
    color: #D2B48C;
    text-decoration: none;
    cursor: pointer;
    font-size: inherit;
}

.terms-link:hover {
    color: #C19A6B;
    text-decoration: underline;
}

/* 注册按钮样式 */
.register-buttons {
    width: 100%;
    display: flex;
    gap: 15px;
}

.submit-btn {
    flex: 1;
    background: #D2B48C;
    border: none;
    border-radius: 4px;
    color: #fff;
    font-weight: 500;
}

.submit-btn:hover {
    background: #C19A6B;
}

.register-buttons .cancel-btn {
    flex: 1;
    border: 1px solid #D2B48C;
    border-radius: 4px;
    color: #8B4513;
    background: #fff;
}

.register-buttons .cancel-btn:hover {
    background: #F5F5F5;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .login-modal {
        width: 90%;
        max-width: 350px;
    }

    .tab-content {
        padding: 15px;
    }

    .register-content {
        padding: 15px;
    }

    .register-title {
        font-size: 16px;
    }
}
</style>